//
//  Tone.m
//  HelloIphone
//
//  Created by Geoffrey Gallaway on 8/1/09.
//  Copyright 2009 TDK Technologies. All rights reserved.
//

#import "Tone.h"


@implementation Tone

@synthesize duration;
@synthesize frequency;
@synthesize volume;
@synthesize samples;
@synthesize numberOfSamples;


-(id)init {
	volume = 100;
	currentSample = 0;
	return self;
}

-(id)initWithFrequency:(Float32)hz duration:(Float32)msecs volume:(Float32)percentage {
	frequency = hz;
	duration = msecs;
	volume = percentage;
	return [self init];
}
-(void)generateTone {
	// 44100 samples per second.. 1/10 of
	// number of samples is 
	numberOfSamples = 44100 * (duration / 1000);
//	numberOfSamples = 44100;//frequency ? (44100.0f / frequency) : 0;
	samples = malloc(sizeof(int) * numberOfSamples);
	for (int i = 0; i < numberOfSamples; i++) {
		float floatVal = sin(((float)i * 2.0 * M_PI * frequency) / 44100.0); // Pitch A
		short sampleValue = (int)(floatVal * 32767.0);
		samples[i] = sampleValue;
	}
	
}

-(float)getNextSample {
	//NSLog(@"Returing sample value: %d", samples[currentSample]);
	if (currentSample >= numberOfSamples-1) {
		currentSample = 0;
		return currentSample;
	}
	return samples[currentSample++];
}

-(BOOL)hasNextSample {
	if (currentSample + 1 >= numberOfSamples-1) {
		currentSample = 0;
		return NO;
	}
	return YES;
}
@end
